package cn.edu.scau.cmi.yangqing.hibernate.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;

import cn.edu.scau.cmi.yangqing.hibernate.domain.Student;

import cn.edu.scau.cmi.yangqing.hibernate.util.HibernateUtil;

public class StudentDao {
	//添加学生
	public void addStudent(Student student) {
		Session session1 = HibernateUtil.getCurrentSessionStu();
		session1.save(student);
	}
	//通过id查找学生
	public Student findStudentById(Integer id) {
		System.out.println("findStudentById");
		Session session = HibernateUtil.getCurrentSessionStu();
		String sql = "select * from student where id = ?";
		NativeQuery query = session.createSQLQuery(sql);
		query.setParameter(1,id);
		query.addEntity(Student.class);
		Student temp = (Student) query.uniqueResult();
		return temp;
	}
	
	public void deleteStudent(Integer id) {
		Session session2 = HibernateUtil.getCurrentSessionStu();
		System.out.println("deleteStudent");
		Student student = new Student();
		student.setId(id);
		session2.delete(student);
	}
	public void updateStudent(Student student) {
		System.out.println("updateStudent");
		Session session = HibernateUtil.getCurrentSessionStu();
		session.update(student);
//		String sql = "update student set name=? where id=?";
//		NativeQuery query = session.createSQLQuery(sql);
//		query.setParameter(1,student.getId());
//		query.setParameter(2, student.getName());
//		query.addEntity(Student.class);
//		query.executeUpdate();
	}
	public List<Student> findAllStudent() {
		System.out.println("findAllStudent");
		Session session = HibernateUtil.getCurrentSessionStu();
		String sql = "select * from student ";
		NativeQuery query = session.createSQLQuery(sql);
		query.addEntity(Student.class);
		List<Student> list = query.getResultList();
		return list;
	}
	public void teachTutor(Integer tutorid, Integer id) {
		System.out.println("teachTutor");
		Session session = HibernateUtil.getCurrentSessionStu();
		String sql = "update student set tutorid=? where id=?";
		NativeQuery query = session.createSQLQuery(sql);
		query.setParameter(1,tutorid);
		query.setParameter(2, id);
		query.addEntity(Student.class);
		query.executeUpdate();
	}
}
